import React, {Component} from 'react';
import GridTable from '../components/display/gridTable';
import ScModal from '../components/feedback/scModal';
import { Button, DatePicker, Input, Select } from 'antd';
import moment from 'moment';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import { getSmsGroupList,
    getUserMenuList,
    addSmsGroupInfo,
    getSmsInfoList,
    sendSmsByGroupId
} from '../fetch/fetchApi';
import PropTypes from "prop-types";
import Tool from "../utils/Tool";
const { RangePicker } = DatePicker;
const TextArea = Input.TextArea;
const Search = Input.Search;
const Option = Select.Option;

class Message extends Component {
    constructor () {
        super();
        this.state = {
            gridData: null,
            detailData: null,
            name: '',
            modalVisible: !1,
            modalTitle: '',
            timePickerVisible: !1,
            confirmLoading: !1,
            loading: !1,
            sendDate: null,
            status: null,
            userId: null,
            pagination: {
                current: 1,
                defaultCurrent: 1,
                defaultPageSize: 10,
                onChange: this.tableChange.bind(this),
                total: 0
            },
            pagination1: {
                current: 1,
                defaultCurrent: 1,
                defaultPageSize: 10,
                onChange: this.tableChange1.bind(this),
                total: 0
            }
        }
      this.init();
      this.beginTime = '';
      this.endTime = '';
    }

    tableChange (e) {
        const page = {...this.state.pagination};
        page.current = e;
        this.setState({
            pagination: page
        });
        this.getSmsGroupListCb(e);
    }

    tableChange1 (e) {
        const page = {...this.state.pagination1};
        page.current = e;
        this.setState({
            pagination1: page
        });
        this.getMessageDetailCb(e);
    }

    static contextTypes = {
        router: PropTypes.object.isRequired
    }

    init () {
        this.title = '运营管理';
        this.subTitle = '短信营销';
        this.selectedKey = ['0101'];
        this.openKeys = ['01'];
        this.detailId = null;
        this.detailParam = {
          smsGroupId: this.detailId,
          userId: null,
          status: null,
          page: 1,
          pagecount: this.state.pagination.defaultPageSize
        };
        this.tableColumns = [
            {
                title: '短信组名称',
                dataIndex: 'name',
                key: 'name',
            }, {
                title: '短信内容',
                dataIndex: 'content',
                key: 'content',
                className: 'column-nowrap'
            },{
                title: '短信运营商',
                dataIndex: 'operatorType',
                key: 'operatorType',
            },{
                title: '发送类型',
                dataIndex: 'sendType',
                key: 'sendType',
            },{
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime',
            },
            {
                title: '发送时间',
                dataIndex: 'sendTime',
                key: 'sendTime',
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => (
                    <div className="action-wrap">
                        <Button type="primary"
                                id={record.key}
                                index={record.index}
                                loading={this.state.gridData[record.index].status === 1 ? !0 : !1}
                                disabled={(this.state.gridData[record.index].status === 2 || this.state.gridData[record.index].status === 1) ? !0: !1}
                                onClick={this.sendMessage.bind(this)}>{this.state.gridData[record.index].sendMes}</Button>
                        <Button type="primary"
                                id={record.key}
                                title="短信详情"
                                onClick={this.showMessageDetail.bind(this)}
                        >查看详情</Button>
                    </div>
                )
            }
        ];
        this.detailColumns = [{
            title: '用户ID',
            dataIndex: 'userId',
            key: 'userId',
        }, {
            title: '发送状态',
            dataIndex: 'mes',
            key: 'mes',
        },{
            title: '短信通道返回码',
            dataIndex: 'msgCode',
            key: 'msgCode',
        }
        ]
    }

    showMessageDetail (e) {
        this.showFlag = !1;
        this.detailId = e.target.id;
        this.detailParam.smsGroupId = this.detailId;
        this.detailParam.status = null;
        this.detailParam.userId = null;
        this.setState({
            width: 820,
            modalVisible: !0,
            modalTitle: e.target.title,
            status: '',
            userId: null
        });
        this.getMessageDetailCb();
    }

  getMessageDetailCb (page) {
    this.setState({
      loading: !0
    });
    page || this.tableChange1(1);
    page && (this.detailParam.page = page);
    this.getMessageDetail(this.detailParam).then(() => {
      this.setState({
        detailData: this.messageDetailList,
        loading: !1
      });
    });
  }

    async getMessageDetail (param) {
        try {
          const resData = await getSmsInfoList(param);
          this.messageDetailList = resData.data.data;
          this.state.pagination1.total = resData.data.pageLimit.totalCount;
          this.setState({
            pagination1: this.state.pagination1
          });
          for (const m of this.messageDetailList) {
                m.msgCode || (m.msgCode = '--');
                switch (m.status) {
                    case 0:
                        m.mes = '未发送';
                        break;
                    case 1:
                        m.mes = '提交成功';
                        break;
                    case 2:
                        m.mes = '提交失败';
                        break;
                    case 3:
                        m.mes = '发送成功';
                        break;
                    case 4:
                        m.mes = '发送失败';
                        break;
                    default:
                        m.mes = '暂无状态';
                }
            }
        }
        catch (e) {
            console.log(e);
        }
    }

    componentDidMount () {
        this.params = {
            sendType: 0
        };
        this.showFlag = !0;
        this.getSmsGroupListCb();
        this.getUserMenuList();
        this.getUserMenuList1();
    }

    getSmsGroupListCb (page) {
        page || this.tableChange(1);
        this.getSmsGroupList(page || 1).then(() => {
          this.setState({
            loading: !1
          });
        });
      }

    async getSmsGroupList (page) {
        this.setState({
          loading: !0
        });
        try {
            const resData = await getSmsGroupList({
                beginTime: this.beginTime,
                endTime: this.endTime,
                page: page,
                pagecount: 10
            });
            let gridData = resData.data.data;
            let index = 0;
            this.state.pagination.total = resData.data.pageLimit.totalCount;
            this.setState({
              pagination: this.state.pagination
            });
            for (let i of gridData) {
                i.operatorType = '美圣';
                i.operatorType === 0 && (i.operatorType = '美圣');
                i.sendType === 0 && (i.sendType = '立即发送');
                i.sendType === 1 && (i.sendType = '定时发送');
                i.status === 0 && (i.sendMes = '发送');
                i.status === 1 && (i.sendMes = '提交中');
                i.status === 2 && (i.sendMes = '提交成功');
                i.status === 3 && (i.sendMes = '重新发送');
                i.index = index;
                index++;
            }
            this.setState({
                modalVisible: !1,
                gridData
            });
        } catch (e) {
            console.log(e);
        }
    }

    async getUserMenuList () {
        try {
            const resData = await getUserMenuList({
                type: 2
            });
            const formatBeforeData = resData.data.data;
            const fromData = JSON.parse(JSON.stringify(formatBeforeData).replace(/id/g,'key').replace(/childList/g, 'children'));
            this.setState({
                fromData
            });
        } catch (e) {
            console.log(e);
        }
    }

    async getUserMenuList1 () {
        try {
            const resData = await getUserMenuList();
            this.setState({
                'menuList': resData.data.data
            });
        } catch (e) {
            console.log(e);
        }
    }

    openNewMessageGp (e) {
        this.showFlag = !0;
        this.setState({
            width: 520,
            modalVisible: !0,
            modalTitle: e.target.title,
            sendDate: null,
            name: e.target.getAttribute('name'),
            content: e.target.getAttribute('content'),
            userIds: e.target.getAttribute('userids')
        });
          this.params = {
            sendType: 0
          };
    }
    async addSmsGroupInfo () {
        this.setState({
            confirmLoading: !0
        });
    try {
        const param = this.params;
        const resData = await addSmsGroupInfo(param);
          this.setState({
            confirmLoading: !1
          });
          if (resData.data.code === '200') {
            this.getSmsGroupListCb();
          }
        } catch (e) {
            console.log(e);
        }
    }

    async sendMessage (e) {
        const index = e.target.getAttribute('index');
        const grid = [...this.state.gridData];
        const params = {};
        grid[index].status === 0 || grid[index].status === 2 &&
        (params.status = 0);
        grid[index].status === 3 && (params.status = 2);
        params.smsGroupId = e.target.id;
        grid[index].status = 1;
        grid[index].sendMes = '发送中';
        this.setState({
            modalVisible: !1,
            gridData: grid
        });
        try {
            const param = params;
            const resData = await sendSmsByGroupId(param);
            resData.data.code === '200' && console.log('send ok');
        } catch (e) {
            console.log(e);
        }
    }

    onDataChange (e) {
        this.beginTime = e && e[0] && e[0].format('YYYY.MM.DD HH:mm:ss').toString();
        this.endTime = e && e[1] && e[1].format('YYYY.MM.DD HH:mm:ss').toString();
        this.getSmsGroupListCb();
    }

    setInputVal (e) {
        this.setState({
            name: e.target.value
        });
        this.params.name = e.target.value;
    }

    setInputContent (e) {
        this.setState({
            content: e.target.value
        });
        this.params.content = e.target.value.replace(/\n/g, '');
        this.params.content = this.params.content.trim();
    }

    setInputUserIds (e) {
        this.setState({
            userIds: e.target.value
        });
        this.params.userIds = e.target.value.replace(/\n/g, '');
        this.params.userIds = this.params.userIds.trim();
    }

    cancel () {
        this.setState({
            modalVisible: !1,
            confirmLoading: !1
        });
    }

  searchByID (e) {
    this.detailParam.smsGroupId = this.detailId;
    this.detailParam.userId = e;
    this.getMessageDetailCb();
  }

  selectChange (e) {
    this.detailParam.smsGroupId = this.detailId;
    this.detailParam.status = e;
    this.setState({
      'status': e
    });
    this.getMessageDetailCb();
  }

  selectSendType (e) {
        this.params.sendType = e;
        const flag = e === '0' ? !1 : !0;
        this.setState({
          timePickerVisible: flag
        });
  }

  disabledDate (current) {
    return current && current < moment().startOf('day');
  }

  disabledTime (current) {
    return current && current < moment().startOf('hour').fromNow();
  }

  pickDate (e) {
    this.params.sendTime = e.format('YYYY.MM.DD HH:mm:ss').toString();
    this.setState({
      sendDate: e
    });
  }

  onSearchHandler(e) {
    this.setState({
      userId: e.target.value
    });
  }

    render () {
        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <RangePicker onChange={this.onDataChange.bind(this)} locale={locale} format="YYYY-MM-DD HH:mm:ss" />
                <Button type="primary"
                        title="新增短信组"
                        name=""
                        content= ""
                        userids=""
                        onClick={this.openNewMessageGp.bind(this)}>新增</Button>
            </div>
            <div className="page-panel">
                <GridTable postyle="table-center" data={this.state.gridData} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
            </div>
        </div>;

        return <div>
            {Content}
            {this.showFlag ?<ScModal
                width={this.state.width}
                modalVisible={this.state.modalVisible}
                modalTitle={this.state.modalTitle}
                modalContent={(<div>
                    <div className="modal-list">
                        <Input placeholder="请输入短信组名称" value={this.state.name} onChange={this.setInputVal.bind(this)} />
                    </div>
                    <div className="modal-list">
                      <Select defaultValue="0" onChange={this.selectSendType.bind(this)} className="modal-select" placeholder="请选择发送类型">
                        <Option value="0">实时发送</Option>
                        <Option value="1">定时发送</Option>
                      </Select>
                    </div>
                  {this.state.timePickerVisible && <div className="modal-list">
                        <DatePicker
                          format="YYYY-MM-DD HH:mm:ss"
                          placeholder="选择发送时间"
                          locale={locale}
                          disabledDate={this.disabledDate}
                          disabledTime = {this.disabledTime}
                          value = {this.state.sendDate}
                          showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                          showToday={false}
                          onOk={this.pickDate.bind(this)}
                          onChange={this.pickDate.bind(this)}
                        />
                      </div>}
                    <div className="modal-list">
                        <TextArea placeholder="请输入短信内容" value={this.state.content} onChange={this.setInputContent.bind(this)} />
                    </div>
                    <div className="modal-list">
                        <TextArea className="bigText" placeholder="用户id集合，多个用英文逗号分割" value={this.state.userIds} onChange={this.setInputUserIds.bind(this)} />
                    </div>
                </div>)}
                handle = {this.addSmsGroupInfo.bind(this)}
                cancel = {this.cancel.bind(this)}
                confirmLoading={this.state.confirmLoading}
              />
              : <ScModal
                width={this.state.width}
                modalVisible={this.state.modalVisible}
                modalTitle={this.state.modalTitle}
                modalContent={(<div className="sc-modal-scroll">
                  <div className="modal-list">
                    <Select onChange={this.selectChange.bind(this)} value={this.state.status} className="modal-select" placeholder="请选择状态">
                      <Option value="">全部状态</Option>
                      <Option value="0">未发送</Option>
                      <Option value="1">提交成功</Option>
                      <Option value="2">提交失败</Option>
                      <Option value="3">发送成功</Option>
                      <Option value="4">发送失败</Option>
                    </Select>
                  </div>
                  <div className="modal-list">
                    <Search
                      value={this.state.userId}
                      onChange={this.onSearchHandler.bind(this)}
                      placeholder="查询用户ID"
                      onSearch={this.searchByID.bind(this)}
                    />
                  </div>
                  <GridTable postyle="table-center" data={this.state.detailData} columns={this.detailColumns} pagination={this.state.pagination1} loading={this.state.loading}/>
                </div>)}
                cancel={this.cancel.bind(this)}
                footer={null}
                />}
        </div>
    }
}

export default Message;